package com.ycc.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ycc.usercenter.common.BaseResponse;
import com.ycc.usercenter.common.ErrorCode;
import com.ycc.usercenter.common.ResultUtils;
import com.ycc.usercenter.exception.BusinessException;
import com.ycc.usercenter.model.domain.DTO.UserLoginRequest;
import com.ycc.usercenter.model.domain.DTO.UserRegisterRequest;
import com.ycc.usercenter.model.domain.User;
import com.ycc.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.ycc.usercenter.constant.UserConstant.ADMIN_USER;
import static com.ycc.usercenter.constant.UserConstant.USER_LOGIN_STATUS;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = {"http://localhost:5173"}, allowCredentials = "true")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.sucess(result);
    }

    @GetMapping("/currentUser")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATUS);
        if (user == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        // TODO 用户状态校验 如是否封号
        User currentUser = userService.getById(user.getId());
        User safetyUser = userService.getSafetyUser(currentUser);
        return ResultUtils.sucess(safetyUser);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.sucess(user);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Integer result = userService.userLogout(request);
        return ResultUtils.sucess(result);
    }

    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "没有登录");
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like(User::getUsername, username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.sucess(list);
    }

    @GetMapping("/recommend")
    public BaseResponse<Page<User>> searchUsers(long pageSize, long pageNum, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        // 设置缓存key
        String key = String.format("recommend:user_id:%d", loginUser.getId());
        ValueOperations valueOperations = redisTemplate.opsForValue();
        // 判断缓存中是否存在
        Page<User> page = (Page<User>) valueOperations.get(key);
        if (page != null && page.getRecords() != null) {
            return ResultUtils.sucess(page);
        }
        // 缓存中不存在则查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        page = userService.page(new Page<>(pageSize, pageNum), queryWrapper);
        List<User> list = page.getRecords().stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        page.setRecords(list);
        // 设置缓存
        try {
            valueOperations.set(key, page , 30000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("redis get set error", e);
        }
        return ResultUtils.sucess(page);
    }

    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchUsersByTags(@RequestParam(required = false) List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        List<User> list = userService.searchUsersByTags(tagNameList);
        return ResultUtils.sucess(list);
    }

    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user, HttpServletRequest request) {
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误");
        }
        User loginUser = userService.getLoginUser(request);
        int result = userService.updateUser(user, loginUser);
        return ResultUtils.sucess(result);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(Long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误");
        }
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "没有权限");
        }
        boolean result = userService.removeById(id);
        return ResultUtils.sucess(result);
    }

}
